package com.admin.client.mvc.views;

import java.util.List;

import com.admin.client.AppConstants;
import com.admin.client.Permisos;
import com.admin.client.components.LoginDialog;
import com.admin.client.components.MenuLateral;
import com.admin.client.locale.AdminConstants;
import com.admin.client.mvc.events.AppEvents;
import com.admin.share.model.MenuDTO;
import com.admin.share.model.UsuarioDTO;
import com.admin.share.services.LoginServiceAsync;
import com.extjs.gxt.ui.client.GXT;
import com.extjs.gxt.ui.client.Registry;
import com.extjs.gxt.ui.client.Style.LayoutRegion;
import com.extjs.gxt.ui.client.Style.Scroll;
import com.extjs.gxt.ui.client.event.BaseEvent;
import com.extjs.gxt.ui.client.event.EventType;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.TabPanelEvent;
import com.extjs.gxt.ui.client.mvc.AppEvent;
import com.extjs.gxt.ui.client.mvc.Controller;
import com.extjs.gxt.ui.client.mvc.Dispatcher;
import com.extjs.gxt.ui.client.mvc.View;
import com.extjs.gxt.ui.client.util.Margins;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.Label;
import com.extjs.gxt.ui.client.widget.LayoutContainer;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.TabItem;
import com.extjs.gxt.ui.client.widget.TabPanel;
import com.extjs.gxt.ui.client.widget.Text;
import com.extjs.gxt.ui.client.widget.Viewport;
import com.extjs.gxt.ui.client.widget.layout.BorderLayout;
import com.extjs.gxt.ui.client.widget.layout.BorderLayoutData;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;
import com.extjs.gxt.ui.client.widget.layout.HBoxLayout;
import com.extjs.gxt.ui.client.widget.layout.HBoxLayoutData;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.RootPanel;

public class AppView extends View{
	private final TabPanel center = new TabPanel();
	private MenuLateral panel = null;

	public AppView(Controller controller) {
		super(controller);		
	}

	@Override
	protected void handleEvent(AppEvent event) {
		EventType eventType = event.getType();
		if(eventType.equals(AppEvents.Init)){
			onInit(event);
		}else if(eventType.equals(AppEvents.Auth)){
			onAuth(event);
		}else if(eventType.equals(AppEvents.Error)){
			onError(event);		
		}else if(eventType.equals(AppEvents.TabSelected)){
			onTabSelected(event);
		}else if(eventType.equals(AppEvents.Permisos)){
			onPermisos(event);
		}
	}
	
	private void onPermisos(AppEvent event) {
		Permisos panel = event.getData();
		Boolean isAdmin = Registry.get(AppConstants.ADMIN);
		List<String> permisos = Registry.get(AppConstants.PERMISOS);
		if(!isAdmin && permisos != null)
			panel.setPermisos(permisos);
	}

	private void onTabSelected(AppEvent event) {
		
		MenuDTO menu = event.getData();
				
		if(panel != null)
			panel.tree.getSelectionModel().deselectAll();
		if(!"inicio".equals(menu.getParametro())){			
			panel.tree.getSelectionModel().select(menu, true);
		}
		
		TabItem tabItem = new TabItem(menu.getMenu());
		tabItem.setId(menu.getParametro());
		tabItem.setData("menu", menu);
		
		tabItem.addListener(Events.Select, new Listener<TabPanelEvent>() {

			@Override
			public void handleEvent(TabPanelEvent be) {				
				TabPanel tp= (TabPanel)be.getSource();
				MenuDTO mn = (MenuDTO)tp.getSelectedItem().getData("menu");
				AppEvent appEvent = new AppEvent(AppEvents.TabSelected, mn);
		    	appEvent.setHistoryEvent(true);
		    	appEvent.setToken(mn.getParametro());		    	
		    	
		    	Dispatcher.forwardEvent(appEvent);				
			}
		});
		if(!menu.getParametro().equals("inicio"))
			tabItem.setClosable(true);
		
		
		addTab(tabItem);
	}
	
	public void addTab(TabItem tabItem){
		tabItem.setLayout(new FitLayout());		
		String tabId = tabItem.getId();
		TabItem existingTab = center.findItem(tabId, false);
		if(existingTab == null){
			loadProgram(tabItem);
			//tabItem.add(new Text(tabId));
			center.add(tabItem);
			center.setSelection(tabItem);
		}else{
			center.setSelection(existingTab);
		}
	}

	private void onAuth(AppEvent event) {
		GXT.hideLoadingPanel("loading");
		LoginDialog dialog = new LoginDialog();
	    dialog.setClosable(false);	    
	    dialog.show();
	}

	private void onError(AppEvent event) {
		final AdminConstants constants = Registry.get(AppConstants.CONSTANTS);
		MessageBox.alert(constants.administradorConsultoriaSTI(), constants.errorConexion(), null);
	}

	private void onInit(AppEvent event) {
		GXT.hideLoadingPanel("loading");
		BorderLayout bl = new BorderLayout();
		Viewport viewport = new Viewport();
		viewport.setLayout(bl);
		
		LayoutContainer north = new LayoutContainer();
		
		ContentPanel west = new ContentPanel();
		final AdminConstants constants = Registry.get(AppConstants.CONSTANTS);
		west.setHeading(constants.principalMenu());
		
		UsuarioDTO result = event.getData();
		
		if(result.getIdprivilegio() == 1)
			Registry.register(AppConstants.ADMIN, true);
		else
			Registry.register(AppConstants.ADMIN, false);
		
		panel = new MenuLateral(result.getId());
		
		west.setScrollMode(Scroll.AUTOY);
	    west.add(panel);	    
	    
	    center.setMinTabWidth(115);  
	    
	    center.setAnimScroll(true);  
	    center.setTabScroll(true);
	    center.setCloseContextMenu(true);	    
	    
	    center.setBounds(10,10,300,300);
		
		BorderLayoutData northData = new BorderLayoutData(LayoutRegion.NORTH, 30);
						
		BorderLayoutData westData = new BorderLayoutData(LayoutRegion.WEST, 200);
		westData.setCollapsible(true);
		westData.setFloatable(true);
		westData.setSplit(true);
		westData.setMargins(new Margins(5, 0, 5, 5));
		
		BorderLayoutData centerData = new BorderLayoutData(LayoutRegion.CENTER);
		centerData.setMargins(new Margins(5));
		
		//norte
		HBoxLayout layout = new HBoxLayout();
		
		north.setLayout(layout);
		Text text = new Text(constants.administradorConsultoriaSTI());
		text.addStyleName("appTitle");
		north.add(text, new HBoxLayoutData());		
		HBoxLayoutData flex = new HBoxLayoutData();  
        flex.setFlex(1);  
        north.add(new Text(), flex);        
        
        Label usuario = new Label(result.getNombres()+" "+result.getApellidos());
        usuario.addStyleName("appUsuario");
        north.add(usuario,new HBoxLayoutData(new Margins(8, 5, 0, 0)));
        
        Label logout = new Label(constants.logout());
        logout.addStyleName("appLogout");
        
        final LoginServiceAsync ls = Registry.get(AppConstants.LOGIN_SERVICE);
        
        logout.addListener(Events.OnClick, new Listener<BaseEvent>() {

			@Override
			public void handleEvent(BaseEvent be) {
				ls.logout(new AsyncCallback<Boolean>() {

					@Override
					public void onFailure(Throwable caught) {
						//Window.alert(constants.errorConexion()+" " + caught.getMessage());						
					}

					@Override
					public void onSuccess(Boolean result) {
						if(!result){
							//MessageBox.alert(constants.sistemaGastos(), "No se pudo cerrar sesion", null);
						}
					}
					
				});
				center.removeAll();
				RootPanel.get().clear();
				Dispatcher.forwardEvent(new AppEvent(AppEvents.Auth, null, "inicio"));
				
			}
        	
		});
        north.add(logout,new HBoxLayoutData(new Margins(8, 5, 0, 0)));
		north.addStyleName("appHeading");
		north.layout();
		
		
		viewport.add(north, northData);
		viewport.add(west, westData);
		viewport.add(center, centerData);		
		RootPanel.get().add(viewport);
	}
	
	public void loadProgram(TabItem tabItem){
		String tabId = tabItem.getId();
		if(tabId.equals("menus")){
			Dispatcher.forwardEvent(new AppEvent(AppEvents.UsuarioReady, tabItem));
		}
	}

}
